package cn.bdqn.controller;

import cn.bdqn.dto.Dto;
import cn.bdqn.pojo.ItripComment;
import cn.bdqn.pojo.ItripHotel;
import cn.bdqn.pojo.ItripImage;
import cn.bdqn.service.HotelService;
import cn.bdqn.service.ItripCommentService;
import cn.bdqn.util.Constant;
import cn.bdqn.util.SFTPUtils;
import cn.bdqn.util.VerificationToken;
import cn.bdqn.vo.ItripAddCommentVo;
import cn.bdqn.vo.ItripHotelVo;
import cn.bdqn.vo.ItripScoreCommentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 2018/8/23
 */
@Api(value = "API", basePath = "")
@RequestMapping("/api/comment")
@Controller
public class ItripCommentController {

    @Resource
    private HotelService hotelService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ItripCommentService itripCommentService;

    @ApiOperation(value = "获取酒店相关信息（酒店名称、酒店星级）", httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "新增评论信息页面内获取酒店相关信息（酒店名称、酒店星级）")
    @RequestMapping(value = "/gethoteldesc/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> getHotelDesc(@ApiParam(required = true, name = "hotelId", value = "酒店ID") @PathVariable Long hotelId) {
        Dto<Object> dto = new Dto<Object>();
        ItripHotelVo itripHotelVo = new ItripHotelVo();
        try {
            if (hotelId!=null) {
                ItripHotel itripHotel = null;
                itripHotel = hotelService.findItripHotelById(hotelId);
                //酒店id
                itripHotelVo.setHotelId(itripHotel.getId());
                //酒店名称
                itripHotelVo.setHotelName(itripHotel.getHotelName());
                //酒店星级
                itripHotelVo.setHotelLevel(itripHotel.getHotelLevel());
            }
            dto.setCode("0000");
            dto.setMsg("查询酒店信息成功");
            dto.setData(itripHotelVo);
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            dto.setCode("10086");
            dto.setMsg("查询失败");
            return dto;
        }
    }

    @RequestMapping(value = "/gethotelscore/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> getHotelScore(@ApiParam(required = true, name = "hotelId", value = "酒店ID")
                                     @PathVariable String hotelId) {
        Dto dto = new Dto();
        if (null != hotelId && !"".equals(hotelId)) {
            ItripScoreCommentVO itripScoreCommentVO = new ItripScoreCommentVO();
            try {
                itripScoreCommentVO = itripCommentService.getAvgAndTotalScore(Long.valueOf(hotelId)).get(0);
                dto.setMsg("获取评分成功");
                dto.setData(itripScoreCommentVO);
            } catch (Exception e) {
                e.printStackTrace();
                dto.setMsg("获取评分失败");
                dto.setCode("100001");
            }
        } else {
            dto.setMsg("获取评分失败");
            dto.setCode("100001");
        }
        return dto;
    }

    @ApiOperation(value = "根据酒店id查询各类评论数量", httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "根据酒店id查询评论数量（全部评论、值得推荐、有待改善、有图片）" +
            "<p>成功：success = ‘true’ | 失败：success = ‘false’ 并返回错误码，如下：</p>" +
            "<p>错误码：</p>" +
            "<p>100014 : 获取酒店总评论数失败 </p>" +
            "<p>100015 : 获取酒店有图片评论数失败</p>" +
            "<p>100016 : 获取酒店有待改善评论数失败</p>" +
            "<p>100017 : 获取酒店值得推荐评论数失败</p>" +
            "<p>100018 : 参数hotelId为空</p>")
    @RequestMapping(value = "/getcount/{hotelId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<Object> getCommentCountByType(@ApiParam(required = true, name = "hotelId", value = "酒店ID")
                                             @PathVariable String hotelId) {
        Dto dto=new Dto();
        if (hotelId == null || hotelId.trim().equals("")) {
            dto.setMsg("hotelId不能为空");
            dto.setCode("10086");
            dto.setSuccess("fail");
            return dto;
        }
        Map<String,Integer> countMap = new HashMap<String,Integer>();
        Integer count1=0;
        Integer count2=0;
        Integer count3=0;
        Integer count4=0;
        Map <String ,Object> map1=new HashMap<>();
        Map <String ,Object> map2=new HashMap<>();
        Map <String ,Object> map3=new HashMap<>();
        Map <String ,Object> map4=new HashMap<>();
        map1.put("hotelId",Long.valueOf(hotelId));
        map2.put("hotelId",Long.valueOf(hotelId));
        map3.put("hotelId",Long.valueOf(hotelId));
        map4.put("hotelId",Long.valueOf(hotelId));
        try {
            //获取总评论数
            count1=hotelService.getHotelCOmmentCountByHotelId(map1);
            countMap.put("allcomment",count1);
            //获取值得推荐评论数
            map2.put("isOk",1);
            count2=hotelService.getHotelCOmmentCountByHotelId(map2);
            countMap.put("isok",count2);
            //获取有待改善评论数
//            map3.put("isOk",0);
//            count3=hotelService.getHotelCOmmentCountByHotelId(map3);
//            System.out.println("改善评论数"+count3);
            countMap.put("improve",count1-count2);
            //获取有图片评论数
            map4.put("isHavingImg",1);
            count4=hotelService.getHotelCOmmentCountByHotelId(map4);
            countMap.put("havingimg",count4);
            dto.setData(countMap);
            dto.setMsg("获取评论数成功");
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            dto.setMsg("未知错误");
            dto.setCode("10086");
            dto.setSuccess("fail");
            return dto;
        }
    }

    /**
     * 酒店点评
     * @param request
     * @param itripAddCommentVo
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Object> add(HttpServletRequest request, @RequestBody ItripAddCommentVo itripAddCommentVo) {
        Dto<Object> dto = new Dto<Object>();
        //只有登录了 才能评论 需要token验证
        String tokenString = request.getHeader("token");
        String userAgentString = request.getHeader("user-Agent");
        VerificationToken verificationToken = new VerificationToken();
        String userId=tokenString.split("-")[2];
        //如果为true
        if (VerificationToken.verification(userAgentString, tokenString)) {

            //得到token里面的对象
           /* ItripUser itripUser = JSON.parseObject((String) redisTemplate.opsForValue().get(tokenString),ItripUser.class);
            System.out.println("11111111111111111111111111111111111111111111哈哈哈"+itripUser);*/


            if (null != itripAddCommentVo) {

                if (itripAddCommentVo.getOrderId() == null || itripAddCommentVo.getOrderId() == 0) {
                    dto.setCode("10086");
                    dto.setMsg("订单号必须填写");
                    dto.setSuccess("false");
                    return dto;
                }

                //将信息存入
                List<ItripImage> itripImages = null;
                ItripComment itripComment = new ItripComment();

                itripComment.setHotelId(itripAddCommentVo.getHotelId());
                itripComment.setHygieneScore(itripAddCommentVo.getHygieneScore());
                itripComment.setIsHavingImg(itripAddCommentVo.getIsHavingImg());
                itripComment.setIsOk(itripAddCommentVo.getIsOk());
                itripComment.setOrderId(itripAddCommentVo.getOrderId());
                itripComment.setPositionScore(itripAddCommentVo.getPositionScore());
                itripComment.setProductId(itripAddCommentVo.getProductId());
                itripComment.setProductType(itripAddCommentVo.getProductType());
                itripComment.setServiceScore(itripAddCommentVo.getServiceScore());
                itripComment.setTripMode(Long.valueOf(itripAddCommentVo.getTripMode()));
                itripComment.setContent(itripAddCommentVo.getContent());
                itripComment.setFacilitiesScore(itripAddCommentVo.getFacilitiesScore());

                itripComment.setCreationDate(new Date(System.currentTimeMillis()));
                itripComment.setCreatedBy(Long.valueOf(userId));
                itripComment.setUserId(Long.valueOf(userId));

                //如果带图片
                try {
                    if (itripAddCommentVo.getIsHavingImg() == 1) {
                        itripImages = new ArrayList<ItripImage>();
                        int i = 1;
                        for (ItripImage itripImage : itripAddCommentVo.getItripImages()) {
                            itripImage.setPosition(i);
                            itripImage.setCreatedBy(Long.valueOf(userId));
                            itripImage.setCreationDate(itripComment.getCreationDate());
                            itripImage.setType("2");
                            itripImages.add(itripImage);
                            i++;
                        }
                    }
                    itripCommentService.addComment(itripComment, null == itripImages ? new ArrayList<ItripImage>() : itripImages);
                    dto.setCode("0000");
                    dto.setMsg("新增评论成功");
                    dto.setSuccess("true");
                    return dto;
                } catch (Exception e) {
                    e.printStackTrace();
                    dto.setCode("10086");
                    dto.setMsg("新增评论失败");
                    dto.setSuccess("false");
                    return dto;
                }

            } else if (null == itripAddCommentVo) {
                //不能提交空的数据
                dto.setMsg("不能提交空的数据");
                dto.setCode("10086");
                dto.setSuccess("false");
                return dto;
            } else {
                dto.setMsg("token失效");
                dto.setCode("10086");
                dto.setSuccess("false");
                return dto;
            }


        }


        return dto;
    }




    /**
     * 图片上传
     * @param
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "图片上传",httpMethod = "post",protocols = "HTTP",produces = "application/json",response = Dto.class)
    @RequestMapping(value = "/upload",method = RequestMethod.POST,produces = "application/json")
    public Dto upload(HttpServletRequest request) throws IOException {
        Dto dto = new Dto();
        if(request.getHeader("token")!=null&&!request.getHeader("token").equals("")){
            String[] userIds = request.getHeader("token").split("-");
            //token:PC-userCode-userID-date-random(6)
            //获得userId
            Long userId = Long.parseLong(userIds[2]);
            List<String> list=new ArrayList<String>(0);
            boolean loginVerify = VerificationToken.verification(request.getHeader("user-agent"), request.getHeader("token"));
            if (loginVerify) {
                StringBuffer sb=new StringBuffer();
                //创建一个通用的多部分解析器
                CommonsMultipartResolver commonsMultipartResolver=new CommonsMultipartResolver(request.getSession().getServletContext());
                //判断request是否有文件上传
                if (commonsMultipartResolver.isMultipart(request)) {
                    //转换成多部分request
                    MultipartHttpServletRequest multiRequest =commonsMultipartResolver.resolveMultipart(request);
                    Iterator<String> ite = multiRequest.getFileNames();
                    while (ite.hasNext()) {
                        MultipartFile file = multiRequest.getFile(ite.next());
                        if (!file.isEmpty()) {
                            if (file.getSize()<4096000&&file.getSize()>0){
                                if(!file.getOriginalFilename().equals("")&&Constant.ImageForm(file.getOriginalFilename())){
                                    //重命名规则：用户 id+当前系统时间+随机数
                                    String newName = sb.append(userId + "-").append(System.currentTimeMillis() + "-").append(Constant.randomTool(6)).toString();
                                    // 获取文件的扩展名
                                    String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                                    // 设置图片上传路径
                                    String name = sb.append(newName).append(ext).toString();
                                    String url = request.getSession().getServletContext().getRealPath("/"+name);
                                    System.out.println(url);
                                    SFTPUtils instance=SFTPUtils.getInstance();
                                    instance.upload(SFTPUtils.directory,url);
                                    //"/data/itrip/img/comment"+name;
                                    //通过CommonsMultipartFile的方法直接写文件
                                    file.transferTo(new File(url));
                                    list.add("/data/itrip/img/comment/"+name);
                                }else {
                                    dto.setCode("10086");
                                    dto.setSuccess("false");
                                    dto.setMsg("上传图片格式不符合");
                                    return dto;
                                }

                            }else {
                                dto.setCode("10086");
                                dto.setSuccess("false");
                                dto.setMsg("上传文件超过大小限制");
                                return dto;
                            }

                        }else {
                            dto.setCode("10086");
                            dto.setSuccess("false");
                            dto.setMsg("上传文件为空");
                            return dto;
                        }
                    }
                }
                dto.setCode("0");
                dto.setMsg("上传成功");
                dto.setSuccess("true");
                dto.setData(list);
                return dto;
            } else{
                dto.setCode("10086");
                dto.setSuccess("false");
                dto.setMsg("账号未登录");
                return dto;
            }
        }else {
            dto.setCode("10086");
            dto.setSuccess("false");
            dto.setMsg("账号未登录");
            return dto;
        }

    }
}
